package com.oweight.sagacious.payment.domain.service.spring;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.github.binarywang.wxpay.bean.request.WxPayMicropayRequest;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayMicropayResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.oweight.sagacious.api.model.msg.Message;
import com.oweight.sagacious.common.context.BaseContextHandler;
import com.oweight.sagacious.payment.domain.entity.WxPayProperties;
import com.oweight.sagacious.payment.domain.model.WeChatPayRefundModel;
import com.oweight.sagacious.payment.domain.model.WeChatPayUnifiedOrder;
import com.oweight.sagacious.payment.domain.service.IWeChatPayManager;
import com.oweight.sagacious.payment.domain.service.IWxPayPropertiesManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 微信统一下单：领域服务实现
 *
 * @author SAGE
 * @version v1 2019-11-15 11:50:05
 */
@Slf4j
@Service
public class WeChatPayManager implements IWeChatPayManager {

    @Autowired
    IWxPayPropertiesManager wxPayPropertiesManager;

    /**
     * 构建微信付款服务
     *
     * @return
     */
    private WxPayService wxPayService() throws Exception {
        WxPayServiceImpl wxPayService = new WxPayServiceImpl();
        WxPayConfig payConfig = new WxPayConfig();

        // todo 需要加缓存！
        String payPropertiesId = String.valueOf(BaseContextHandler.get("wx_pay_config_id"));
        WxPayProperties wxPayProperties = wxPayPropertiesManager.getByFdId(payPropertiesId);

        if (wxPayProperties == null) {
            log.error("微信付款：没有找到支付配置！");
            throw new Exception("微信付款：没有找到支付配置！");
        }

        BeanUtil.copyProperties(wxPayProperties, payConfig, CopyOptions.create().ignoreNullValue().ignoreError());

        payConfig.setKeyPath("/home/dell/data/IdeaProjects/vz-sagacious/sage-payment/src/main/resources/apiclient_cert.p12");
        wxPayService.setConfig(payConfig);

        return wxPayService;
    }

    @Override
    public Message order(WeChatPayUnifiedOrder order, String clientIp) {
        Message message = new Message();

        // 微信支付
        WxPayUnifiedOrderRequest wxPayUnifiedOrder = WxPayUnifiedOrderRequest.newBuilder().build();
        wxPayUnifiedOrder.setBody(order.getBody());
        wxPayUnifiedOrder.setOutTradeNo(order.getOutTradeNo());
        wxPayUnifiedOrder.setTotalFee(order.getTotalFee());
        wxPayUnifiedOrder.setNotifyUrl(order.getNotifyUrl());
        wxPayUnifiedOrder.setSpbillCreateIp(clientIp);

        String tradeType = order.getTradeType();
        wxPayUnifiedOrder.setTradeType(tradeType);
        log.info("交易类型：" + tradeType);

        Object result;
        try {
            // 商家扫码支付
            String authCode = order.getAuthCode();
            if (StrUtil.isNotBlank(authCode)) {
                log.info("商家扫码支付...");
                // openid = wxPayService().authcode2Openid(authCode);

                WxPayMicropayRequest wxPayMicropayRequest = new WxPayMicropayRequest();
                BeanUtil.copyProperties(order, wxPayMicropayRequest);

                WxPayMicropayResult microPay = wxPayService().micropay(wxPayMicropayRequest);
                return message.ok("商家扫码支付OK").data(microPay);
            }

            // 判断当前付款模式
            String openid = order.getOpenid();
            String subAppId = wxPayService().getConfig().getSubAppId();
            if (StrUtil.isNotBlank(subAppId)) {
                log.info("服务商模式");
                wxPayUnifiedOrder.setSubOpenid(openid);
            } else {
                log.info("普通模式");
                wxPayUnifiedOrder.setOpenid(openid);
            }
            result = wxPayService().createOrder(wxPayUnifiedOrder);

        } catch (WxPayException e) {
            log.error("微信付款：服务端下单失败！", e);
            return message.error("微信付款：" + e.getReturnMsg());
        } catch (Exception e) {
            log.error("微信付款：服务端下单失败！", e);
            return message.error("服务端下单失败！" + e.getLocalizedMessage());
        }

        log.info("微信付款：服务端下单成功！");
        return message.ok("微信付款：服务端下单成功！").data(result);
    }

    @Override
    public Message refund(WeChatPayRefundModel refundModel) {
        Message message = new Message();

        WxPayRefundRequest refundRequest = new WxPayRefundRequest();
        BeanUtil.copyProperties(refundModel, refundRequest);

        WxPayRefundResult refund = null;
        try {
            refund = wxPayService().refund(refundRequest);

        } catch (Exception e) {
            log.error("微信付款：服务端退款失败！", e);
            message.error("微信付款：服务端退款失败！");
        }
        log.info("微信付款：服务端退款成功！");
        return message.ok("微信付款：服务端退款成功！").data(refund);

    }

    @Override
    public Message sweepCodePayment() {
        return null;
    }
}
